package api

import (
	"net/http"

	"GinAdmin/core/logger"
	"GinAdmin/model"
	"GinAdmin/service"

	"github.com/gin-gonic/gin"
)

// AuthAPI 认证API控制器
type AuthAPI struct {
	userService *service.UserService
}

// NewAuthAPI 创建认证API控制器
func NewAuthAPI() *AuthAPI {
	return &AuthAPI{
		userService: service.NewUserService(),
	}
}

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录并返回JWT令牌
// @Tags 认证
// @Accept json
// @Produce json
// @Param data body model.LoginRequest true "登录请求"
// @Success 200 {object} model.Response "登录成功"
// @Failure 400 {object} model.Response "请求错误"
// @Failure 401 {object} model.Response "登录失败"
// @Router /api/auth/login [post]
func (a *AuthAPI) Login(c *gin.Context) {
	var req model.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, model.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	token, user, err := a.userService.Login(req.Username, req.Password)
	if err != nil {
		logger.Error("用户登录失败: %v", err)
		c.JSON(http.StatusUnauthorized, model.Response{
			Code: 401,
			Msg:  "登录失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.Response{
		Code: 200,
		Msg:  "登录成功",
		Data: gin.H{
			"token": token,
			"user":  user,
		},
	})
}

// Register 用户注册
// @Summary 用户注册
// @Description 注册新用户
// @Tags 认证
// @Accept json
// @Produce json
// @Param data body model.RegisterRequest true "注册请求"
// @Success 200 {object} model.Response "注册成功"
// @Failure 400 {object} model.Response "请求错误"
// @Router /api/auth/register [post]
func (a *AuthAPI) Register(c *gin.Context) {
	var req model.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, model.Response{
			Code: 400,
			Msg:  "请求参数错误: " + err.Error(),
		})
		return
	}

	user, err := a.userService.Register(&req)
	if err != nil {
		logger.Error("用户注册失败: %v", err)
		c.JSON(http.StatusBadRequest, model.Response{
			Code: 400,
			Msg:  "注册失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, model.Response{
		Code: 200,
		Msg:  "注册成功",
		Data: user,
	})
}
